//
//  PaperRecordViewModel.swift
//  Exam-iOS
//
//  Created by lishengfeng on 2018/3/24.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import RxDataSources

class PaperRecordViewModel: LSFRefreshProtocol {
    var vmData = Variable([PaperRecordSection]())
    var pageNum = 1
    var requestCommand = PublishSubject<Bool>()
    var disposeBag = DisposeBag()
    
    var refreshStatus = Variable(LSFRefreshStatus.none)
    
    ///是否是空数据
    var isNull = Variable<Bool>(false)
    
    init() {
        requestCommand.subscribe(onNext: { (isPull) in
            if isPull {
                self.pageNum = 1
            }
            self.recordList()
        }).disposed(by: disposeBag)
    }
    
    func recordList() {
        paperProvider.rx
            .request(.recordList(pageNum: pageNum, pageSize: 10))
            .asObservable()
            .mapRespnseToObjectArray(type: PaperRecordModel.self).subscribe(onNext: { (models) in
            
            let sections = self.vmData.value
            var section = sections.first
            if sections.count == 0 {
                section = PaperRecordSection.init(items: [PaperRecordModel]())
            }

            if self.pageNum == 1 {
                section?.items.removeAll()
            }
            if models.count > 0 {
                section?.items.append(contentsOf: models)
                self.pageNum += 1
            }
            self.vmData.value = [section!]
            
        }, onError: { (error) in
            stopAnimating()
            showError(error)
            self.refreshStatus.value = .endHeaderRefresh
            self.refreshStatus.value = .endFooterRefresh
        }, onCompleted: { [weak self] in
            stopAnimating()
            self?.isNull.value = (self?.vmData.value.first?.items.count == 0)
            self?.refreshStatus.value = .endHeaderRefresh
            self?.refreshStatus.value = .endFooterRefresh
        }).disposed(by: disposeBag)
    }
}

struct PaperRecordSection {
    var items: [PaperRecordModel]
}
extension PaperRecordSection: SectionModelType {
    typealias Item = PaperRecordModel
    init(original: PaperRecordSection, items: [PaperRecordModel]) {
        self = original
        self.items = items
    }
}
